package com.gmscosmo.sdk;

import com.alibaba.fastjson.JSONObject;
import com.gmscosmo.common.IMResult;
import com.gmscosmo.reflect.TypeBuilder;
import com.google.gson.Gson;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.reflect.Type;


public class JanusHttpUtils {
    private static final Logger LOG = LoggerFactory.getLogger(JanusHttpUtils.class);

    private static String adminUrl;
    private static String adminSecret;

    public static void init(String url, String secret) {
        adminUrl = url;
        adminSecret = secret;
    }

    public static <T> IMResult<T> httpJsonPost(String path, Object object, Class<T> clazz) throws Exception{
        if (isNullOrEmpty(adminUrl) || isNullOrEmpty(adminSecret)) {
            LOG.error("音视频SDK必须先初始化才能使用!!");
            throw new Exception("SDK没有初始化");
        }

        if (isNullOrEmpty(path)) {
            throw new Exception("路径缺失");
        }
        String url = adminUrl + path;
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        int nonce = (int)(Math.random() * 100000 + 3);
        long timestamp = System.currentTimeMillis();
        String str = nonce + "|" + adminSecret + "|" + timestamp;
        String sign = DigestUtils.sha1Hex(str);
        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);

        httpPost.setHeader("Content-type", "application/json; charset=utf-8");
        httpPost.setHeader("Connection", "Keep-Alive");
        httpPost.setHeader("nonce", nonce + "");
        httpPost.setHeader("timestamp", "" + timestamp);
        httpPost.setHeader("sign", sign);

        String jsonString = JSONObject.toJSONString(object);
        StringEntity entity = new StringEntity(jsonString, "UTF-8");

        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);

        // 响应模型
        CloseableHttpResponse response = null;
        IMResult var = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            var =  fromJsonObject(EntityUtils.toString(responseEntity),clazz);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return var;
    }

    private static <T> IMResult<T> fromJsonObject(String content, Class<T> clazz) {
        Type type = TypeBuilder
                .newInstance(IMResult.class)
                .addTypeParam(clazz)
                .build();
        return new Gson().fromJson(content, type);
    }

    private static boolean isNullOrEmpty(String str) {
        return str == null || str.isEmpty();
    }

}
